#This is a sample script to generate a TNT batchfile for real template artificial extinction experiments. 
#The output of this script is a series of TNT commands in a single text (batch) file and a metadata csv file with information #for each fossil template including the Pattinson et al (2015) Q metric 
#Script received by Robert J. Asher, Dept Zoology, University of Cambridge on the 19th of March 2020 and then adapted for use in this thesis
#Please do not distribute without permission from Robert J. Asher

#needs these libraries to run
library(tidyverse)
library(phangorn)

#test matrix
matrix<-read.nexus.data("sampleMatrix.nex") #This is to give R metadata for morph matrix including all taxa. Note read.nexus.data cannot read multistates so any "[01]" etc has to be converted to ? or one of the polymorphisms; see ?read.nexus.data
tnames<-attr(matrix,"names") #put taxon names into "tnames"
dfmatrix<-data.frame(matrix)
rtxbatch<-"rtxBatch.txt"
rtxmeta<-"rtxMeta.csv"

#write initial TNT commands to batch file 
write(paste("mxram 500","\n",			#adjust mxram for your dataset, with nstates <8 TNT will tell you how much RAM is needed (but doesn't give accurate values when nstates>8)
            "log testfile.log","\n",    #so TNT writes details of search to a logfile which you'll want to rename 
            "taxname=;","\n",sep = ""),file = rtxbatch,append = T)	#to ensure taxnames are readable (otherwise they're numbers)
#add subject/template taxon data here
starttemplate=62	#first fossil (= template)
endtemplate=124 	#last fossil
startsubject=2 		#put outgroup at row #1 so this starts at 2nd extant taxon (= subject)
endsubject=61 		#last subject
#add morph partition data here. This block writes a csv file with %complete, Q value (as explained in Pattinson et al. 2015)
morphtotal = length(dfmatrix[,1])
#nonoverlapping character partitions only. Change according to your matrices
part1=c(1:87) #jaw-dent
part2=c(88:165) #cranium
part3=c(166:219) #postcrania
partnames<-cbind(c("part1","part2","part3"), c("jaw-dent","cranium","postcran"))
write(paste("template","missing","complete", partnames[1,2],partnames[2,2],partnames[3,2],"pQosteo",sep = ","),rtxmeta,append = T)

#loop writes both TNT script for Ntemplate x Nsubject analyses and csv file with metadata for each template
for (i in starttemplate:endtemplate) {
  for (x in startsubject:endsubject) {
    template<-tnames[i]
    subject<-tnames[x]
    chars<-dfmatrix[,i]
    string<-paste(chars,collapse = "")
    qmarks<-str_locate_all(string,"\\?") #to search for "?" use "\\?". to search for multiple strings use c("string1","string2"...) 
	qm<-data.frame(qmarks[1]) #convert into df & read only non-redundant start positions in qs$start
    qmTNT<-qm$start-1 #TNT numbers from 0; qm$start should be used for nexus-numbered (from #1) comparisons
    write(paste("proc sampleComb.tnt;","\n",
                "taxcode -{fossils};","\n",
				"hold 1000;","\n",
                "xread=[",sep = ""),file = rtxbatch,append = T)
    write(paste(qmTNT, collapse=" ",sep = " "),file = rtxbatch,append = T)
	 # to exclude a block of DNA chars from the TNT runs replace "748.3366]" w/ your DNA block (or define (DNA) in a TNT "xgroup" block)
    write(paste(" 219.16137] ", x-1," ?;", "\n", 
	 #next line defines the TNT search
                "mult=rep 100 hold 10; bbreak=tbr; nelsen *;","\n",
                "export - rtx",subject,"_",template,".out; tchoose -.;","\n", sep = ""),file = rtxbatch, append = T)
  }
# metadata for each template, PC = percent
# NOTE values may differ from original matrix when using version with multistates converted to "?" (as required by read.matrix)
  PCmorph<-(morphtotal-length(qm$start))/morphtotal*100
  PCpart1<-(length(part1)-sum((qm$start %in% part1)))/length(part1)*100
  PCpart2<-(length(part2)-sum((qm$start %in% part2)))/length(part2)*100
  PCpart3<-(length(part3)-sum((qm$start %in% part3)))/length(part3)*100
  pQost<-((PCpart1/100)*(PCpart2/100)+(PCpart1/100)*(PCpart3/100)+(PCpart2/100)*(PCpart3/100))/3+0.0001
  write(paste(template,length(qmTNT),PCmorph,PCpart1,PCpart2,PCpart3,pQost,sep = ","),file = rtxmeta,append = T)
}

#close TNT log file
write(paste("log /;",sep = ""),file = rtxbatch,append = T)
